package com.ifcar.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;

import com.ifcar.app.bean.DetailPageBean;
import com.ifcar.app.bean.MicroHotBean;
import com.ifcar.app.bean.OlympicGameScheduleBean;
import com.ifcar.app.rss.GetColumnsInfo;

import com.netease.util.Pair;

public class FileUtils {
	public static String FileTempDir = "/sdcard/netease/newsreader/netease_temp_file/";
	public static String DetailPageTempDir = "/sdcard/netease/newsreader/netease_temp_file/detail_page/";
	public static String OlympicGameScheduleTempDir = "/sdcard/netease/newsreader/netease_temp_file/olympic_game_schedule/";
	public static String NewsListTempDir = "/sdcard/netease/newsreader/netease_temp_file/news_list/";
	public static long EXPIRE = 2;//过期日期为3天
	
    public static long getFileSizes(File f) throws Exception{//取得文件大小
        long s=0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s= fis.available();
        } else {
            f.createNewFile();
        }
        return s;
    }
    // 递归
    public static long getFileSize(File f)throws Exception//取得文件夹大小
    {
        long size = 0;
        if(!f.exists()) return size;      
        
        try {
            File flist[] = f.listFiles();
            for (int i = 0; i < flist.length; i++)
            {
                if (flist[i].isDirectory())
                {
                    size = size + getFileSize(flist[i]);
                } else
                {
                    size = size + flist[i].length();
                }
            }
        }catch (java.lang.OutOfMemoryError error){
            
        }catch (Exception e) {
        
        }
        
        return size;
    }

    public static String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = "0K";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
	
	public static boolean isSDCardMounted() {
		String sDStateString = android.os.Environment.getExternalStorageState();
		if(sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isSDCardMountedReadOnly() {
		String sDStateString = android.os.Environment.getExternalStorageState();
		if(sDStateString.equals(android.os.Environment.MEDIA_MOUNTED_READ_ONLY)) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isFileExit(String filename){
		boolean s = false;
	
		try {
			File file = new File(filename);
			s = file.exists();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return s;
	}
	
	public static boolean deleteFile(File file) {
		if(isSDCardMounted()) {
			if (file.exists()) {
				try {
					if (file.isFile()) {
						file.delete();
					} else if (file.isDirectory()) {
						File files[] = file.listFiles();
						for (int i = 0; i < files.length; i++) {
							deleteFile(files[i]);
						}
						file.delete();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}
				return true;
			} else {
				return true;
			}
		} else return false;

	}
	
	public static boolean autoDeleteCacheFile(File file, long expiredDuration) {
		if(isSDCardMounted()) {
			if (file.exists() && file.isDirectory()) {
				try {
					File[] files = file.listFiles();
					for(int i=0; files!=null && i<files.length; i++) {
						if(files[i].isFile() && System.currentTimeMillis() - files[i].lastModified() 
								>= expiredDuration) {
							files[i].delete();
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}
				return true;
			} else {
				return true;
			}
		} else return false;

	}
	
	public static boolean createFile(String filepath){

		File file = new File(filepath);
		
		
		if((isSDCardMounted() || isSDCardMountedReadOnly()) && file.exists()){
			return true;
		}else{
			try {
				if(isSDCardMounted()) {
					return file.createNewFile();
				}else return false;
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				return false;
			}
		}
	}
	
	public static boolean createFolder(String filepath){
		
		File file = new File(filepath);
		
		if((isSDCardMounted() || isSDCardMountedReadOnly()) && file.exists()){
			return true;
		}else{
			if(isSDCardMounted()) {
				return file.mkdirs();
			} else return false;
			
		}
	}
	
	public static void delFile(String strFileName) {
		if(isSDCardMounted()) {
			try {
				File myFile = new File(strFileName);
				if (myFile.exists()) {
					myFile.delete();
				}
			} catch (Exception e) {
			}
		}

	}
	
	public static Map<String, Object> readDetailPageData(String id) {
        String filepath = DetailPageTempDir + id;
        
        Map<String, Object> map = null;
        if(isSDCardMounted() || isSDCardMountedReadOnly()) {
    		if(isFileExit(filepath)) {
    			try {
    				FileInputStream fi = new FileInputStream(filepath);
    				ObjectInputStream dataI = new ObjectInputStream(fi);

    				DetailPageBean bean = (DetailPageBean) dataI.readObject();

    				if (null != bean) {
    					map = bean.getData();
    				}
    			} catch (Exception e) {
                    e.printStackTrace();
    			}
    		}
        } 
        
        return map;
	}

	public static void writeDetailPageData(Map<String, Object> data, String id) {
		String filepath = DetailPageTempDir + id;
		if(isSDCardMounted()) {
			try {
			    delFile(filepath);
				if (!isFileExit(filepath) && null != data && !data.isEmpty() 
						&& createFolder(DetailPageTempDir)) {

					FileOutputStream fo = new FileOutputStream(filepath);
					ObjectOutputStream dataO = new ObjectOutputStream(fo);

					DetailPageBean bean = new DetailPageBean();

					bean.setData(data);

					dataO.writeObject(bean);

					fo.close();				
								
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block			
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}
	
	private static StringBuilder imgSrc = null;
	public static void writeDetailPageData4OfflineThread(HashMap<String, Object> data, String id,Context mContext,String columnid) {
		String filepath = DetailPageTempDir + id;
		if(isSDCardMounted()) {
			try {
				if (!isFileExit(filepath) && null != data && !data.isEmpty() 
						&& createFolder(DetailPageTempDir)) {

					FileOutputStream fo = new FileOutputStream(filepath);
					ObjectOutputStream dataO = new ObjectOutputStream(fo);

					DetailPageBean bean = new DetailPageBean();

					bean.setData(data);

					dataO.writeObject(bean);

					fo.close();		
					if (data.get(GetColumnsInfo.IMG_TAG) != null) {
						List<HashMap<String, Object>> imgList = (ArrayList)data.get(GetColumnsInfo.IMG_TAG);
						HashMap<String, Object> imgMap = new HashMap<String, Object>();			
						int length = imgList.size();
						for (int i = 0; i < length; i++) {
							imgMap = imgList.get(i);
							imgSrc = new StringBuilder(""+imgMap.get(GetColumnsInfo.SRC_TAG));
							imgSrc.insert("http://".length(), "s.cimg.163.com/i/");
							imgSrc.append(".220x220.auto.jpg");

							if (!PicUtil.isLocalPicExit(imgSrc.substring(imgSrc
									.lastIndexOf("/") + 1, imgSrc.length()))) {
								
								final String imgUrl = imgSrc.toString();
								final String imgName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1, imgSrc.length());
								final Context _context = mContext;
								new Thread() {
									public void run() {		
									    PicUtil.downloadImgToLocal(imgUrl,_context);
									}
								}.start();
							}
						}
						imgList.clear();
					}
								
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	
	public static void delDetailPageData(String id) {
        String filepath = DetailPageTempDir + id;
        delFile(filepath);
	}
	
	public static int clearCacheFolder(final File dir) {

	    int deletedFiles = 0;
	    if (dir!= null && dir.isDirectory() && dir.exists()) {
	        try {
	            for (File child:dir.listFiles()) {

	            	if (child.getName().toLowerCase().equals("webviewcache")) {
		                //first delete subdirectories recursively
		                if (child.isDirectory()) {
		                    deletedFiles += clearCacheFolder(child);
		                }

	                    if (child.delete()) {
	                        deletedFiles++;
	                    }
	            	}

	            	
	            }
	        }
	        catch(Exception e) {
	           
	        }
	    }
	    return deletedFiles;
	}

	/*
	 * Delete the files older than numDays days from the application cache
	 * 0 means all files.
	 */
	public static void clearCache(final Context context) {
	  
	    int numDeletedFiles = clearCacheFolder(context.getCacheDir());
	    context.deleteDatabase("webview.db");
	    context.deleteDatabase("webviewCache.db");
	}
	
	public static void autoClearCache(){
	    
	    File temppath = new File(FileTempDir);
	    excuteClear(temppath);
	    File detailpagepath = new File(DetailPageTempDir);
        excuteClear(detailpagepath);
	    
	}
	
	private static void excuteClear(File path){
	    
	    if(path.exists() && path.isDirectory()){
	           long currentdate = new Date().getTime();
	           File files[] =  path.listFiles();
	           if(null!=files){
	               int length = files.length;
	               for(int index=0;index<length;index++){
	                   File one = files[index];
	                   clearFile(one,currentdate);
	               }
	           }
	           
	        }
	}
	
	private static void clearFile(File file,long currentdate){
	    
	    if(null!=file && file.exists() && file.isFile()){
	        long filetime = file.lastModified();
	        long  expire = (currentdate - filetime)/(24*60*60*1000);
	        if(expire>EXPIRE){
	            file.deleteOnExit();
	        }
	        
	    }
	}

	public static class DownloadThread extends Thread{
	    private Context mContext;
	    private List<HashMap<String, Object>> imgList;
	    
	    public DownloadThread(Context context,List<HashMap<String, Object>> mimgList){
	        mContext = context;
	        imgList = mimgList;
	    }
	    
	    public void run(){
	        HashMap<String, Object> imgMap;  
            int length = imgList.size();
            for (int i = 0; i < length; i++) {
                imgMap = imgList.get(i);
                imgSrc = new StringBuilder(""+imgMap.get(GetColumnsInfo.SRC_TAG));
                imgSrc.insert("http://".length(), "s.cimg.163.com/i/");
                imgSrc.append(".220x220.auto.jpg");

                try {
                    if (!PicUtil.isLocalPicExit(imgSrc.substring(imgSrc
                            .lastIndexOf("/") + 1, imgSrc.length()))) {
                        
                         String imgUrl = imgSrc.toString();
                        PicUtil.downloadImgToLocal(imgUrl,mContext);
                       
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            imgList.clear();
	    }
	}
	
	public static class BitmapOfflineDownloaderTask extends AsyncTask<List<HashMap<String, Object>>, Void, Void> {
	    private Context mContext;
	    public BitmapOfflineDownloaderTask(Context context){
	        mContext = context;
	    }
	    @Override
        protected Void doInBackground(List<HashMap<String, Object>>... params) {
            // TODO Auto-generated method stub
            HashMap<String, Object> imgMap;  
            List<HashMap<String, Object>> imgList =  params[0];
            int length = imgList.size();
            for (int i = 0; i < length; i++) {
                imgMap = imgList.get(i);
                imgSrc = new StringBuilder(""+imgMap.get(GetColumnsInfo.SRC_TAG));
                imgSrc.insert("http://".length(), "s.cimg.163.com/i/");
                imgSrc.append(".220x220.auto.jpg");

                try {
                    if (!PicUtil.isLocalPicExit(imgSrc.substring(imgSrc
                            .lastIndexOf("/") + 1, imgSrc.length()))) {
                        
                         String imgUrl = imgSrc.toString();
                        PicUtil.downloadImgToLocal(imgUrl,mContext);
                       
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            imgList.clear();
            return null;
        }
	    
	};
	
	/**
	 * 将微新闻数据本地化
	 * @param list
	 * @param microhot_tag
	 * @param mContext
	 */
	public static void writeMicroHotToLocal(List<Pair<Map<String, Object>, List<Map<String, Object>>>> list, String microhot_tag, Context mContext) {
        String filepath = DetailPageTempDir + microhot_tag;
        
        if(isSDCardMounted()) {
            try {
            	
            	delFile(filepath);
            	
                if (!isFileExit(filepath) && null != list && !list.isEmpty() 
                        && createFolder(DetailPageTempDir)) {

                    FileOutputStream fo = new FileOutputStream(filepath);
                    ObjectOutputStream dataO = new ObjectOutputStream(fo);
                    
                    MicroHotBean bean = new MicroHotBean();
                    
                    int len = list.size();
                    bean.setLengh(len);
                    
                    for(int i = 0; i < len; i ++){
                    	Pair<Map<String, Object>, List<Map<String, Object>>> p = list.get(i);
                    	bean.addGroup(i, p.first);
                    	bean.addChild(i, p.second);
                    }
                    
                    dataO.writeObject(bean);
                    dataO.flush();
                    dataO.close();
                    fo.close();
                }
            } catch (Exception e) {
				// TODO: handle exception
			}
        }
	}
	
	/**
     * 将微新闻数据本地化
     * @param list
     * @param microhot_tag
     * @param mContext
     */
    public static void writeOlympicGameScheduleToLocal(List<Pair<Map<String, Object>, List<Map<String, Object>>>> list, String itemName, Context mContext) {
        String filepath = OlympicGameScheduleTempDir + itemName;
        
        if(isSDCardMounted()) {
            try {
                
                delFile(filepath);
                
                if (!isFileExit(filepath) && null != list && !list.isEmpty() 
                        && createFolder(OlympicGameScheduleTempDir)) {

                    FileOutputStream fo = new FileOutputStream(filepath);
                    ObjectOutputStream dataO = new ObjectOutputStream(fo);
                    
                    OlympicGameScheduleBean bean = new OlympicGameScheduleBean();
                    
                    int len = list.size();
                    bean.setLengh(len);
                    
                    for(int i = 0; i < len; i ++){
                        Pair<Map<String, Object>, List<Map<String, Object>>> p = list.get(i);
                        bean.addGroup(i, p.first);
                        bean.addChild(i, p.second);
                    }
                    
                    dataO.writeObject(bean);
                    dataO.flush();
                    dataO.close();
                    fo.close();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
    
	
	/**
	 * 读取微新闻数据
	 * @param micro_tag
	 * @return
	 */
	public static List<Pair<Map<String,Object>, List<Map<String,Object>>>> readMicroHotData(String micro_tag) {
        String filepath = DetailPageTempDir + micro_tag;
        
        if(isSDCardMounted() || isSDCardMountedReadOnly()) {
    		if(isFileExit(filepath)) {
    			try {
    				FileInputStream fi = new FileInputStream(filepath);
    				ObjectInputStream dataI = new ObjectInputStream(fi);
    				
    				MicroHotBean bean = (MicroHotBean) dataI.readObject();
    				
    				if (null != bean) {
    					
    				    List<Pair<Map<String, Object>, List<Map<String, Object>>>> list = new ArrayList<Pair<Map<String, Object>, List<Map<String, Object>>>>();
    					
    					int len = bean.getLength();
    					for(int i = 0; i < len; i ++){
    						Pair<Map<String,Object>, List<Map<String,Object>>> p = Pair.create(bean.getGroup(i), bean.getChild(i));
    						list.add(p);
    					}
    					
    					return list;
    				} else {
    					return null;
    				}
    				
    			} catch (Exception e) {
                    e.printStackTrace();
    				return null;
    			}
    		} else {
    			return null;
    		}
        } 
        return null;
	}
	
	   /**
     * 读取奥运赛程数据
     * @param micro_tag
     * @return
     */
    public static List<Pair<Map<String,Object>, List<Map<String,Object>>>> readGameScheduleData(String day_tag) {
        String filepath = OlympicGameScheduleTempDir + day_tag;
        
        if(isSDCardMounted() || isSDCardMountedReadOnly()) {
            if(isFileExit(filepath)) {
                try {
                    FileInputStream fi = new FileInputStream(filepath);
                    ObjectInputStream dataI = new ObjectInputStream(fi);
                    
                    OlympicGameScheduleBean bean = (OlympicGameScheduleBean) dataI.readObject();
                    
                    if (null != bean) {
                        
                        List<Pair<Map<String,Object>, List<Map<String,Object>>>> list = new ArrayList<Pair<Map<String, Object>, List<Map<String, Object>>>>();
                        
                        int len = bean.getLength();
                        for(int i = 0; i < len; i ++){
                            Pair<Map<String,Object>, List<Map<String,Object>>> p = Pair.create(bean.getGroup(i), bean.getChild(i));
                            list.add(p);
                        }
                        
                        return list;
                    } else {
                        return null;
                    }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                return null;
            }
        } 
        return null;
    }
	
	/**
	 * 将搜索历史数据本地化
	 * @param list
	 * @param search_tag
	 * @param mContext
	 */
	public static void writeSearchHistoryToLocal(List<String> list, String search_tag, Context mContext) {
        String filepath = DetailPageTempDir + search_tag;
        
        if(isSDCardMounted()) {
            try {
            	
            	delFile(filepath);
            	
                if (!isFileExit(filepath) && null != list && !list.isEmpty() 
                        && createFolder(DetailPageTempDir)) {

                    FileOutputStream fo = new FileOutputStream(filepath);
                    ObjectOutputStream dataO = new ObjectOutputStream(fo);
                    
                    dataO.writeObject(list);
                    dataO.flush();
                    dataO.close();
                    fo.close();
                }
            } catch (Exception e) {
				// TODO: handle exception
			}
        }
	}
	
	/**
	 * 读取搜索历史
	 * @param search_tag
	 * @return
	 */
	public static List<String> readSearchHistoryData(String search_tag) {
        String filepath = DetailPageTempDir + search_tag;
        
        if(isSDCardMounted() || isSDCardMountedReadOnly()) {
    		if(isFileExit(filepath)) {
    			try {
    				FileInputStream fi = new FileInputStream(filepath);
    				ObjectInputStream dataI = new ObjectInputStream(fi);
    				
    				List<String> list = (List<String>) dataI.readObject();
    				
    				return list;
    			} catch (Exception e) {
                    e.printStackTrace();
    				return null;
    			}
    		} else {
    			return null;
    		}
        } 
        return null;
	}
	
}
